package cn.xiaopengstack.domain.strategy.service.rule.tree.impl;

import cn.xiaopengstack.domain.strategy.model.valobj.AwardStockQueueVO;
import cn.xiaopengstack.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import cn.xiaopengstack.domain.strategy.model.valobj.StrategyAwardDecrStockVO;
import cn.xiaopengstack.domain.strategy.repository.IStrategyRepository;
import cn.xiaopengstack.domain.strategy.service.armory.IStrategyDispatch;
import cn.xiaopengstack.domain.strategy.service.rule.tree.ILogicTreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@Component("rule_stock")
@Slf4j
public class RuleStockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IStrategyRepository strategyRepository;

    @Resource
    private IStrategyDispatch strategyDispatch;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(DefaultTreeFactory.TreeActionMatterEntity treeMatter) {
        int derStock = treeMatter.getDerNumber();
        // 库存扣减
        boolean decrStockResult = strategyDispatch.subtractionAwardStock(
                treeMatter.getStrategy().getStrategyId(),
                treeMatter.getAwardId(),
                derStock);

        // 扣减库存成功
        if (decrStockResult) {
            log.info("规则过滤-库存扣减-成功。userId:{} strategyId:{} awardId:{}", treeMatter.getUser().getUserId(), treeMatter.getStrategy().getStrategyId(), treeMatter.getAwardId());

            // 发送扣减库存队列
            strategyRepository.produceStrategyAwardDecrStockQueue(AwardStockQueueVO.builder()
                            .strategyId(treeMatter.getStrategy().getStrategyId())
                            .awardId(treeMatter.getAwardId())
                            .decrStock(derStock).build());

            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                    .strategyAwardVo(DefaultTreeFactory.StrategyAwardVO.builder()
                            .awardId(treeMatter.getAwardId())
                            .build()).build();
        }

        log.warn("规则过滤-库存扣减-告警，库存不足。userId:{} strategyId:{} awardId:{}", treeMatter.getUser().getUserId(), treeMatter.getStrategy().getStrategyId(), treeMatter.getAwardId());
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                .strategyAwardVo(DefaultTreeFactory.StrategyAwardVO.builder()
                        .build()).build();
    }
}
